﻿using System;
using System.Xml.Linq;

namespace Songhay.Xml
{

    /// <summary>
    /// Static helper members for XML-related routines.
    /// </summary>
    public static partial class XObjectUtility
    {
        /// <summary>
        /// Gets the element or attribute value of the specified element.
        /// </summary>
        /// <param name="currentElement">The current element.</param>
        /// <param name="xpathQuery">The xpath query.</param>
        public static string GetValue(XElement currentElement, string xpathQuery)
        {
            return GetValue(currentElement, xpathQuery, true);
        }

        /// <summary>
        /// Gets the element or attribute value of the specified element.
        /// </summary>
        /// <param name="currentElement">The current element.</param>
        /// <param name="xpathQuery">The xpath query.</param>
        /// <param name="throwException">if set to <c>true</c> throw exception.</param>
        public static string GetValue(XElement currentElement, string xpathQuery, bool throwException)
        {
            var node = XObjectUtility.GetXObject(currentElement, xpathQuery);
            if(node == null)
            {
                if(throwException) throw new ArgumentNullException("The XPath query returns a null node");
                else return null;
            }

            if(node.NodeType == System.Xml.XmlNodeType.Element)
                return (node as XElement).Value;
            else if(node.NodeType == System.Xml.XmlNodeType.Attribute)
                return (string)XObjectUtility.GetXAttributeValue(currentElement, xpathQuery, throwException);
            else
                return null;
        }
    }
}
